/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;

/**
 *
 * @author shone
 */
public class CommandLineInterface {

    /**
     * 
     * @param command absolute path to executable file
     * @param args array of arguments to be passed to executable file
     * @return output generated by the executed string
     * @throws ExecuteException
     * @throws IOException
     */
    public static synchronized String execute(String command, String[] args)
            throws ExecuteException, IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        String ret = "";

        CommandLine cl = CommandLine.parse(command);
        cl.addArguments(args, true);

        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        exec.setStreamHandler(new PumpStreamHandler(byteStream));

        System.out.println("EXEC: " + command);

        if(args != null) {
            System.out.println("ARGS: ");
            for (int i = 0; i < args.length; i++) {
                System.out.println(args[i]);
            }
        }
        
        System.out.println("IZVRSAVAM: " + cl.toString());

        exec.execute(cl);
        ret = byteStream.toString();

        try {
            byteStream.close();
        } catch(IOException ex) {
            ex.printStackTrace();
        }

        return ret;
    }

}
